<?php

namespace app\admin\model;


/**
 * Author:Jack Wang
 * Time:2018-10-18 17:14:23
 * Describe:图纸库模型
 * Class DrawingBank
 * @package app\admin\model
 */
class DrawingBank extends Base
{
    protected $autoWriteTimestamp = true;//开启自动添加时间戳
    protected $updateTime = false;

    /**
     * Author:Jack Wang
     * Time:2018-10-19 09:27:49
     * Describe:检查库图纸是否存在
     * @param int $draw_id
     * @param string $no
     * @param string $no2
     * @return int|string
     */
    public function checkDrawOnly($draw_id = 0,$no = '',$no2 = ''){
        return $this
            ->where(function ($q)use ($draw_id){
                if(!empty($draw_id)){
                    $q->where('draw_id',$draw_id);
                }
            })
            ->where(function ($q)use($no,$no2){
                if(!empty($no)){
                    $q->where('no',$no);
                }
                if(!empty($no2)){
                    $q->where('no2',$no2);
                }
            })
            ->count();
    }

    //图纸库列表
    public function drawingBankList($keyword = "",$cate = "",$layct = ""){
        return $this
            ->alias("a")
            ->fieldRaw("a.*,IFNULL(b.drawing_id,0) drawing_id")
            ->join($this->prefix."drawing b","a.drawing_bank_id = b.drawing_bank_id",'left')
            ->where(function ($q)use ($keyword){
                if(!empty($keyword)){
                    //模糊查找支持标题和编号
                    $q->whereOr("a.no",'like','%'.$keyword.'%')->whereOr("a.topic",'like','%'.$keyword.'%');
                }
            })
            ->where(function ($q)use ($cate){
                if(!empty($cate)){
                    //分类查找
                    $q->where("a.cate",$cate);
                }
            })
            ->where(function ($q)use ($layct){
                if(!empty($layct)){
                    //楼层查找
                    $fristLayct = substr($layct, 0, 1);//获取第一个字符串,判断条件
                    if((int)$fristLayct > 0){//是否3层以上
                        $q->where("a.layct",$layct);
                    }else{
                        $q->where("a.layct",$fristLayct,substr($layct, 1, strlen($layct) - 1));
                    }
                }
            })
            ->orderRaw("if(b.drawing_id > 0,1,0) ASC,a.create_time DESC")
            ->page($this->after_page)
            ->limit($this->after_limit)
            ->select();
    }

    /**
     * Author:Jack Wang
     * Time:2018-10-19 10:42:05
     * Describe:图纸库列表总数
     * @param string $keyword
     * @param string $cate
     * @param string $layct
     * @return int|string
     */
    public function drawingBankListCount($keyword = "",$cate = "",$layct = ""){
        return $this
            ->where(function ($q)use ($keyword){
                if(!empty($keyword)){
                    //模糊查找支持标题和编号
                    $q->whereOr("no",'like','%'.$keyword.'%')->whereOr("topic",'like','%'.$keyword.'%');
                }
            })
            ->where(function ($q)use ($cate){
                if(!empty($cate)){
                    //分类查找
                    $q->where("cate",$cate);
                }
            })
            ->where(function ($q)use ($layct){
                if(!empty($layct)){
                    //楼层查找
                    $fristLayct = substr($layct, 0, 1);//获取第一个字符串,判断条件
                    if((int)$fristLayct > 0){//是否3层以上
                        $q->where("layct",$layct);
                    }else{
                        $q->where("layct",$fristLayct,substr($layct, 1, strlen($layct) - 1));
                    }
                }
            })
            ->count();
    }

    /**
     * Author:Jack Wang
     * Time:2018-10-22 10:12:25
     * Describe:获取配置参数列表
     * @param string $filed
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function drawingBankConfigList($filed = 'no2'){
        return $this->field([$filed."_name as config_name"])->group($filed)->select();
    }

    /**
     * Author:Jack Wang
     * Time:2018-10-22 10:47:11
     * Describe:添加图纸配置参数
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function drawingBankConfigAdd($data){
        $DrawingConfigurationParameter = config("DrawingConfigurationParameter");//获取图纸配置参数
        foreach ($DrawingConfigurationParameter as $key=>$val){//遍历配置参数，所有配置参数检测，没有添加
            $list = [];
            foreach ($data as $dataKey=>$dataVal){
                $state = true;//重复值游标
                foreach ($list as $listVal){//循环变量,已有值不添加
                    //属性特殊处理
                    if($DrawingConfigurationParameter["attrs"] == $val){
                        $state = false;//属性处理默认false
                        if(!empty($dataVal["attrs"]) && !empty($dataVal["attrsData"])){//不为空的属性值
                            foreach ($dataVal["attrsData"] as $attrsDataVal){//遍历attrsData对象
                                if ($listVal['config_name'] != $attrsDataVal["config_name"] && !empty($attrsDataVal["config_name"])) {//判断值是否重复,或者是否为空
                                    $list[]['config_name'] = $attrsDataVal["config_name"];
                                }
                            }
                        }
                    }else {//非属性值处理
                        if ($listVal['config_name'] == $dataVal[$key . "_name"]) {//判断值是否重复,或者是否为空
                            $state = false;
                        }
                    }
                }
                //不重复值添加|或者是否为空
                if($state && (!empty($dataVal[$key."_name"]))) {
                    $list[]['config_name'] = $dataVal[$key . "_name"];
                }
                //属性特殊处理添加
                if($state && $DrawingConfigurationParameter["attrs"] == $val){
                    if(!empty($dataVal["attrs"]) && !empty($dataVal["attrsData"])){//不为空的属性值
                        foreach ($dataVal["attrsData"] as $attrsDataVal){//遍历attrsData对象
                            if (!empty($attrsDataVal["config_name"])) {//判断值是否重复,或者是否为空
                                $list[]['config_name'] = $attrsDataVal["config_name"];
                            }
                        }
                    }
                }
            }
            $Config = new Config();
            $result = $Config->drawingApiConfigAdd($val,$list);//添加配置类型参数
        }
        //循环需要插入的数组
        foreach ($data as $key=>$val){
            $Config = new Config();
            foreach ($DrawingConfigurationParameter as $configKey=>$configVal){//遍历配置参数，所有配置参数检测
                //属性特殊处理
                if($DrawingConfigurationParameter["attrs"] == $configVal){
                    $attrsStr = '';//新属性
                    $attrsData = [];
                    if(!empty($val["attrs"]) && !empty($val["attrsData"])){//不为空的属性值
                        foreach ($val["attrsData"] as $attrsDataKey=>$attrsDataVal){//遍历attrsData对象
                            if (!empty($attrsDataVal["config_name"])) {//判断值是否重复,或者是否为空
                                $configId = $Config->getConfigId($attrsDataVal["config_name"]);
                                $attrsStr .= "[".$configId."]";//属性赋值
                                //属性附加赋值
                                $attrsData[$attrsDataKey]['config_id'] = $configId;
                                $attrsData[$attrsDataKey]['config_name'] = $attrsDataVal["config_name"];
                            }
                        }
                    }
                    $data[$key]['attrs'] = $attrsStr;//属性赋值
                    $data[$key]['attrsData'] = json_encode($attrsData);//转化成为json，属性附加赋值
                }
                if(!empty($val[$configKey."_name"])){
                    $configId = $Config->getConfigId($val[$configKey."_name"]);
                    $data[$key][$configKey] = $configId;
                }
            }
        }
        return $data;
    }

    /**
     * Author:Jack Wang
     * Time:2018-11-05 17:02:18
     * Describe:添加图纸配置参数（NEW）
     * 添加配置新方法从接口获取
     * @param $data
     * @return mixed
     */
    public function drawingBankConfigAddNew($data){
        $rs = action('Drawings/getDrawingConfig');//自动同步配置参数
        $DrawingConfigurationParameter = config("DrawingConfigurationParameter");//获取图纸配置参数
        $Config = new Config();
        foreach ($data as $DataKey=>$DataVal){
            $attrsData = [];//属性附加数组
            foreach ($DrawingConfigurationParameter as $key=>$val) {//遍历配置参数
                if($DrawingConfigurationParameter["attrs"] == $val){//是否是图纸属性
                    if(!empty($DataVal["attrs"]) && !empty($DataVal["attrsData"])) {//图纸属性不为空
                        $ids = "";
                        foreach ($DataVal["attrsData"] as $ATDKey=>$ATDVal){//遍历图纸属性
                            $id = $Config->getConfigId($ATDVal["config_name"]);//获取配置参数名称
                            $ids .= "[".$id."]";
                            $attrsData[$ATDKey]["config_id"] = $id;
                        }
                        $data[$DataKey][$key] = $ids;
                    }
                }else{
                    $data[$DataKey][$key] = $Config->getConfigId($DataVal[$key."_name"]);//获取配置参数名称
                }
            }
            $data[$DataKey]['attrsData'] = json_encode($attrsData);//转化成为json，属性附加赋值
        }
        return $data;
    }

    //更新图纸基础信息
    public function updateAllDrawingBank($data){
        $count = [0,0];
        $Drawing = new Drawing();
        foreach ($data as $key => $val){
            //去掉不存在字段
            unset($val["ctime"]);
            unset($val["cate_name"]);
            unset($val["mtime"]);
            unset($val["no2_name"]);
            unset($val["struct_name"]);
            unset($val["style_name"]);
            $drawing_bank_id = $this->where("no",$val["no"])->where("no2",$val["no2"])->value("drawing_bank_id");
            if(!empty($drawing_bank_id)) {
                if ($this->mySave($val, "drawing_bank_id", $drawing_bank_id)) {
                    ++$count[0];
                    $val["drawing_bank_id"] = $drawing_bank_id;
                    unset($val["draw_id"]);//去掉接口图纸id
                    unset($val["attrsData"]);//去掉data
                    if($Drawing->updateAllDrawingBank($val)) {
                        ++$count[1];
                    }
                }
            }
        }
        return $count;
    }
}